package com.hongdee.base.car.service.impl;

import com.hongdee.base.Constant;
import com.hongdee.base.car.dao.ICarDao;
import com.hongdee.base.car.entity.TBcCar;
import com.hongdee.base.car.entity.TBcCarTwo;
import com.hongdee.base.car.service.ICarService;
import com.hongdee.base.carmodel.service.ICarModelService;
import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by My on 2017/2/13.
 */
@Service
public class CarServiceImpl implements ICarService {
    @Autowired
    private ICarDao carDao;
    private String tabName = "T_BC_CAR_SERIES";
    private String entity = "TBcCar";
    private List<String> deptList;
    @Autowired
    private ICarModelService iCarModelService;

    /**
     * @param start       当前页面
     * @param limit       页面大小
     * @param bCode       品牌编码
     * @param carModule   车辆型号名称
     * @param carModuleNo 车辆型号代码
     * @param type        类型 0车系1车型
     * @return Map
     * @throws Exception
     * @desc 分页查询
     * @author 徐钦勇
     */
    @Override
    public Map page(String start, String limit, String bCode, String carModule, String carModuleNo, String type, String carSeriesCode, String allSeries) throws Exception {
        String sql = "select * from " + tabName + " where 1=1 ";
        Map map = new HashMap();
        List params = new ArrayList();
        if (type.equals("0")) {
            if ("0".equals(allSeries)) {
                sql += "  and (sale_status = 1 or sale_status = 0) ";
            }
        }
        if("0".equals(type)){
            sql+=" and sale_status = 1 ";
            if("1".equals(allSeries)){
                sql += " ";
            }
            if (!StringUtils.isEmpty(bCode)) {
                sql += " and brand_code = ? ";
                params.add(bCode);
            }
            if (!StringUtils.isEmpty(carModule)) {
                sql += " and car_series_name like ? ";
                params.add("%" + carModule + "%");
            }
            sql += " and type = ? ";
            params.add(type);
        }
        if (type.equals("1")) {
            sql+=" and sale_status = 1 ";
            if (!StringUtils.isEmpty(carSeriesCode)) {
                sql += " and p_car_series like ? ";
                params.add("%" + carSeriesCode + "%");
            }
            if (StringUtils.isEmpty(carSeriesCode)) {
                sql += " 1=0 ";
            }
            sql += " and type = ? ";
            params.add(type);
        }
        sql+="";
        map = this.carDao.page(sql, params.toArray(), start, limit);
        return map;
    }

    /**
     * 加厂牌号的查询
     * @param uid
     * @param showLevel
     * @param allSeries
     * @param allFlag
     * @return
     * @throws Exception
     */
    @Override
    public List pages( String uid, int showLevel, String allSeries, boolean allFlag) throws Exception{

        ///根据登录人员过滤
        List<Map> all = new ArrayList<>();
        Map mapBrand = null;
//        List<Map<String,Object>> mapList=TokenUtil.getDataCompany(uid);
//        //品牌
        List<Map> brand = AllBrand();
//        for(Map c:mapList) {
//            String carBrand=StringUtil.formatEmpty(c.get("oCarBrand"));
//            Map<String, String> c = TokenUtil.getCompany(uid);
            for (Map temp : brand) {
//                if(!"QT".equals(StringUtil.formatEmpty(temp.get("bCode")))) {
//                    if (!allFlag) {
//                        if (!"0".equals(uid) && !temp.get("bCode").equals(carBrand)) {
//                            continue;
//                        }
//                    }
//                }
//                boolean flag=this.checkBrand(all,temp);
//                if(!flag){
//                    continue;
//                }
                mapBrand = new HashMap();
                List<Map> series = new ArrayList<>();
                //车系
                List<Map> tempSeries = CarSeriesNumber(String.valueOf(temp.get("bCode")), allSeries);
                for (Map tempS : tempSeries) {
                    Map mapSeries = new HashMap();
                    mapSeries.put("label", tempS.get("seriesNameNumber"));
                    mapSeries.put("value", tempS.get("id"));
                    mapSeries.put("code", tempS.get("carSeriesCode"));
                    mapSeries.put("number",tempS.get("labelNumber"));
                    //车系
                    mapSeries.put("type", "1");

                    if (showLevel > 1) {
                        mapSeries.put("child", iCarModelService.buildTreeNodeLists(tempS.get("id").toString(), String.valueOf(temp.get("bCode")), showLevel));
                    }
                    series.add(mapSeries);
                }
                if(series.size()>0) {
                    //品牌
                    mapBrand.put("type", "0");
                    mapBrand.put("label", temp.get("bName"));
                    mapBrand.put("value", temp.get("bCode"));
                    mapBrand.put("child", series);
                    all.add(mapBrand);
                }
//            }
        }
        return all;
    }

    /**
     * 查询车系（加厂牌号）
     * @param bc
     * @param allSeries
     * @return
     * @throws Exception
     */
    private List CarSeriesNumber(String bc, String allSeries) throws Exception {

        List params = new ArrayList();

        String sql = "select *," +
                "if(label_number is not null and label_number <>'',CONCAT(car_series_name,'(',label_number,')'),CONCAT(car_series_name,'')) seriesNameNumber"+
                " from t_bc_car_series where brand_code = ? and ( sale_status = '1'  ";
        params.add(bc);
        if ("0".equals(allSeries)) {
            sql += " or sale_status = '0'";
        }
        if("1".equals(allSeries)){
            sql += " ";
        }
        sql+=")";
        return this.carDao.list(sql, params.toArray());
    }
    /**
     * @param id 主键
     * @return Map
     * @throws Exception
     * @desc 车型车系详细
     * @author 徐钦勇
     */
    @Override
    public Map info(String id) throws Exception {
        if (StringUtils.isEmpty(id)) {
            throw new Exception("请选择记录");
        }
        String sql = "select * from " + tabName + " where id = ? ";
        return this.carDao.info(sql, new Object[]{id});
    }

    /**
     * @param brandCode 品牌编码
     * @return List
     * @throws Exception
     * @desc 车系下拉列表
     * @author 徐钦勇
     */
    @Override
    public List<Map> combo(String brandCode, String companyId) throws Exception {


        String sql = " select * from " + tabName + " where res_status=1 and type=0 and brand_code = " +
                "(select o_car_brand from t_bc_organ where id=?)  ";
        List<Map<String, Object>> mapList = this.carDao.list(sql, companyId);
        List<Map> resList = new ArrayList<Map>();
        Map temp;
        for (Map map : mapList) {
            temp = new HashMap();
            temp.put("value", map.get("carSeriesCode"));
            temp.put("label", map.get("carSeriesName"));
            resList.add(temp);
        }
        return resList;
    }

    /**
     * @param id     主键
     * @param status 状态
     * @return Map
     * @throws Exception
     * @desc 启用停用
     * @author 徐钦勇
     */
    @Override
    public void update(String id, String status) throws Exception {
        if (StringUtils.isEmpty(id)) {
            throw new Exception("请选择记录");
        }
        String hql = "update " + entity + " set res_status = :status where id = :id ";
        Map params = new HashMap();
        params.put("id", id);
        params.put("status", status);
        this.carDao.update(hql, params);
    }

    /**
     * @param data 实体
     * @return TBcCar
     * @throws Exception
     * @desc 保存或修改
     * @author 徐钦勇
     */
    @Override
    public TBcCar saveOrUpdate(TBcCar data) throws Exception {
        if (null == data.getId() || StringUtils.isEmpty(data.getId())) {
            //新增时判断是否已经存在
            if (existCarSeriesCode(data.getCarSeriesCode(), data.getId(), Constant.ADD,data.getBrandCode()) && data.getType().equals("0")) {
                throw new Exception("该车系编号已经存在");
            }
            if (existCarTypeCode(data.getCarTypeCode(), data.getId(), Constant.ADD) && data.getType().equals("1")) {
                throw new Exception("该车型代码已经存在");
            }
            data.setSaleStatus("1");
        } else {
            if (existCarSeriesCode(data.getCarSeriesCode(), data.getId(), Constant.UPDATE,data.getBrandCode()) && data.getType().equals("0")) {
                throw new Exception("该车系编号已经存在");
            }
            if (existCarTypeCode(data.getCarTypeCode(), data.getId(), Constant.UPDATE) && data.getType().equals("1")) {
                throw new Exception("该车型代码已经存在");
            }
        }

        data.setResStatus("1");
        return (TBcCar) this.carDao.saveOrUpdate(data);
    }

    private boolean existCarSeriesCode(String gCode, String id, int type,String brandCode) throws Exception {
        String sql = "select * from " + tabName + " where car_series_code = ? ";
        List param = new ArrayList();
        param.add(gCode);
        if (type == Constant.UPDATE) {

            sql += " and type = '0' and id != ? and res_status='1' and brand_code= ?";
            param.add(id);
            param.add(brandCode);
        }
        Map map = this.carDao.page(sql, param.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;
    }

    private boolean existCarTypeCode(String gCode, String id, int type) throws Exception {
        String sql = "select * from " + tabName + " where car_type_code = ? ";
        List param = new ArrayList();
        param.add(gCode);
        if (type == Constant.UPDATE) {

            sql += " and id != ? ";
            param.add(id);
        }
        Map map = this.carDao.page(sql, param.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;
    }

    private List<Map<String, Object>> buildDeptParent(List<Map<String, Object>> paranet) throws Exception {
        if (paranet.size() == 0) {
            return paranet;
        }
        String pId;
        for (Map<String, Object> temp : paranet) {
            pId = String.valueOf(temp.get("id"));
            List<Map<String, Object>> childList = buildDeptChild(pId);
            temp.put("child", childList);
            deptList.add(pId);
        }
        return paranet;
    }

    private List<Map<String, Object>> buildDeptChild(String opId) throws Exception {
        String sqlStr = "select * from t_bc_organ  where o_p_id = ? ";
        List<Map<String, Object>> child = this.carDao.list(sqlStr, opId);
        return buildDeptParent(child);
    }

    /**
     * 根据等级、公司品牌查询车型
     *
     * @param companyId
     * @param level
     * @return
     */
    @Override
    public List<Map> queryByLevel(String companyId, String level) throws Exception {
        String sql = " select car_series_name,car_series_code from " + tabName + " where res_status=1 and type=0 and brand_code =" +
                "(select o_car_brand from t_bc_organ where id=?) and car_series_level = ?  ";
        List<Map<String, Object>> mapList = this.carDao.list(sql, companyId, level);
        List<Map> resList = new ArrayList<Map>();
        for (Map map : mapList) {
            Map temp = new HashMap();
            temp.put("label", String.valueOf(map.get("carSeriesName")));
            temp.put("value", String.valueOf(map.get("carSeriesCode")));
            resList.add(temp);
        }
        return resList;
    }

    /**
     * 获取全部品牌资源
     */
    private List AllBrand() throws Exception {
        return this.carDao.list("select * from t_bc_brand where status = 1 and b_code not in('BX') ");
    }

    /**
     * 查询车系
     */
    private List CarSeries(String bc, String allSeries) throws Exception {

        List params = new ArrayList();

        String sql = "select * from t_bc_car_series where brand_code = ? and type = '0' and res_status = '1' and  ( sale_status = '1'  ";
        params.add(bc);
        if ("0".equals(allSeries)) {
            sql += " or sale_status = '0'";
        }
        if("1".equals(allSeries)){
            sql += " ";
        }
        sql+=")";
        return this.carDao.list(sql, params.toArray());
    }

    /**
     * 方法名称: treeCarModle
     * 方法描述: 查询车型
     **/
    @Override
    public List treeCarModle(String pCarSeries) throws Exception {
        String sqlStr = "select * from t_bc_car_series  where p_car_series = ? and type= '1' ";
        List<Object> param = new ArrayList();
        param.add(pCarSeries);
        List<Map<String, Object>> treeP = this.carDao.list(sqlStr, param.toArray());
        return treeP;
    }

    /**
     * 树形结构拼接
     */
    @Override
    public List tree() throws Exception {
        //品牌
        List<Map> brand = AllBrand();
        List<Map> all = new ArrayList<>();

        for (Map temp : brand) {
            Map mapBrand = new HashMap();
            List<Map> series = new ArrayList<>();
            //车系
            List<Map> tempSeries = CarSeries(String.valueOf(temp.get("bCode")), "null");
            for (Map tempS : tempSeries) {
                Map mapSeries = new HashMap();
                mapSeries.put("label", tempS.get("carSeriesName"));
                mapSeries.put("value", tempS.get("carSeriesCode"));
                //车系
                mapSeries.put("type", "1");
                series.add(mapSeries);
            }
            //品牌
            mapBrand.put("type", "0");
            mapBrand.put("label", temp.get("bName"));
            mapBrand.put("value", temp.get("bCode"));
            mapBrand.put("child", series);
            all.add(mapBrand);
        }
        return all;
    }


    @Override
    public List buildCarLevelTree(String uid, int showLevel, String allSeries, boolean allFlag) throws Exception {

        ///根据登录人员过滤
        List<Map> all = new ArrayList<>();
        Map mapBrand = null;
//        List<Map<String,Object>> mapList=TokenUtil.getDataCompany(uid);
//        for(Map c:mapList) {
            //品牌
            List<Map> brand = AllBrand();
            for (Map temp : brand) {
//                if(!allFlag){
//                  if(!"0".equals(uid)){
//                        continue;
//                  }
//                }
//                boolean flag=this.checkBrand(all,temp);
//                if(!flag){
//                    continue;
//                }
                mapBrand = new HashMap();
                List<Map> series = new ArrayList<>();
                //车系
                List<Map> tempSeries = CarSeries(String.valueOf(temp.get("bCode")), allSeries);
                for (Map tempS : tempSeries) {
                    Map mapSeries = new HashMap();
                    mapSeries.put("label", tempS.get("carSeriesName"));
                    mapSeries.put("value", tempS.get("id"));
                    mapSeries.put("code", tempS.get("carSeriesCode"));
                    //车系
                    mapSeries.put("type", "1");

                    if (showLevel > 1) {
                        mapSeries.put("child", iCarModelService.buildTreeNodeList(tempS.get("id").toString(), String.valueOf(temp.get("bCode")), showLevel));
                    }
                    series.add(mapSeries);
                }
                if(series.size()>0) {
                    //品牌
                    mapBrand.put("type", "0");
                    mapBrand.put("label", temp.get("bName"));
                    mapBrand.put("value", temp.get("bCode"));
                    mapBrand.put("child", series);
                    all.add(mapBrand);
                }
//            }
        }
        return all;
    }

    /**
     * 品牌车系树
     * @param uid
     * @param showLevel
     * @param allSeries
     * @param allFlag
     * @return
     * @throws Exception
     */
    @Override
    public List buildLevelTree(String uid, int showLevel, String allSeries, boolean allFlag,String brandCode) throws Exception{

        ///根据登录人员过滤
        List<Map> all = new ArrayList<>();
        Map mapBrand = null;
        //获取兼营品牌+自营品牌
        List<Map<String,Object>> mapList = new ArrayList<>();
        if(brandCode==null||"".equals(brandCode)){//全查
            mapList= this.getCarBrand(uid);
        }else{//单个查
            Map map = new HashMap();
            map.put("carBrand",brandCode);
            mapList.add(map);
        }
        for(Map c:mapList) {
            //品牌
            List<Map> brand = AllBrand();
            for (Map temp : brand) {
                if(!allFlag){
                    if(!"0".equals(uid)&&!temp.get("bCode").equals(c.get("carBrand"))){
                        continue;
                    }
                }
                boolean flag=this.checkBrand(all,temp);
                if(!flag){
                    continue;
                }
                mapBrand = new HashMap();
                List<Map> series = new ArrayList<>();
                //车系
                List<Map> tempSeries = CarSeries(String.valueOf(temp.get("bCode")), allSeries);
                for (Map tempS : tempSeries) {
                    Map mapSeries = new HashMap();
                    mapSeries.put("label", tempS.get("carSeriesName"));
                    mapSeries.put("value", tempS.get("id"));
                    mapSeries.put("code", tempS.get("carSeriesCode"));
                    //车系
                    mapSeries.put("type", "1");

                    if (showLevel > 1) {
                        mapSeries.put("child", iCarModelService.buildTreeNodeList(tempS.get("id").toString(), String.valueOf(temp.get("bCode")), showLevel));
                    }
                    series.add(mapSeries);
                }
                if(series.size()>0) {
                    //品牌
                    mapBrand.put("type", "0");
                    mapBrand.put("label", temp.get("bName"));
                    mapBrand.put("value", temp.get("bCode"));
                    mapBrand.put("child", series);
                    all.add(mapBrand);
                }
            }
        }
        return all;
    }

    /**
     * 获取兼营品牌+自营品牌
     * @param uid
     * @return
     * @throws Exception
     */
    private List<Map<String,Object>> getCarBrand(String uid) throws Exception{

        List<Map<String,Object>> list = new ArrayList<>();
        List<Map<String,Object>> mapList=TokenUtil.getDataCompany(uid);
        for(Map<String,Object> map:mapList){
            Map mm = new HashMap();
            mm.put("carBrand",map.get("oCarBrand"));
            list.add(mm);
        }
        //查看公司是否兼营品牌
        if(this.carDao.info("select * from t_bc_organ where id=? and run_brands='1'",TokenUtil.getCompanyId(uid)).size()>0){
            List<Map<String,Object>> brandList = this.carDao.list("select * from t_bc_run_brands where o_id=? and type='1'",TokenUtil.getCompanyId(uid));
            for(Map<String,Object> map:brandList){
                Map mm = new HashMap();
                mm.put("carBrand",map.get("brandCode"));
                list.add(mm);
            }
        }
        return list;
    }
    private boolean checkBrand(List<Map> all,Map temp){
        for(Map a:all){
            if(StringUtil.formatEmpty(a.get("value")).equals(StringUtil.formatEmpty(temp.get("bCode")))){
                return false;
            }
        }
        return true;
    }



    @Override
    public TBcCar getInfo(String id) throws Exception {
        return this.carDao.info(id);
    }

    @Override
    public TBcCar getInfoByCode(String code) throws Exception {
        return this.carDao.infoByCode(code);
    }

    /***
     * 根据公司 ID，查询公司信息
     * @param companyId
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, String> getOrgInfo(String companyId) throws Exception {
        String sql = " select * from t_bc_organ where id = ? ";
        return this.carDao.info(sql, companyId);
    }


}
